package com.petshop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.petshop.mapper.AddressMapper;
import com.petshop.pojo.Address;
import com.petshop.service.AddressService;
import com.petshop.utils.JwtHelper;
import com.petshop.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 20289
 * @description 针对表【address】的数据库操作Service实现
 * @createDate 2025-03-10 14:57:29
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address>
        implements AddressService {
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private JwtHelper jwtHelper;

    /**
     * 新增一条地址信息
     *
     * @param address
     * @return
     */
    @Override
    public Result insertAddress(Address address, String token) {
        int userId = jwtHelper.getUserId(token).intValue();
        address.setUserId(userId);
        int insert = addressMapper.insert(address);
        if (insert > 0) {
            return Result.ok("新增成功！");
        }
        return Result.error("插入失败！");
    }

    /**
     * 删除地址信息
     *
     * @param addressId
     * @return
     */
    @Override
    public Result deleteAddress(Integer addressId) {
        int i = addressMapper.deleteById(addressId);
        if (i > 0) {
            return Result.ok("删除成功");
        }
        return Result.error("删除失败！请重试");
    }

    /**
     * 修改地址信息
     *
     * @param address
     * @return
     */
    @Override
    public Result updateAddress(Address address) {
        int i = addressMapper.updateById(address);
        if (i > 0) {
            return Result.ok("修改成功");
        }
        return Result.error("修改失败！请重试");
    }

    /**
     * 查询所有地址信息
     *
     * @param token
     * @return
     */
    @Override
    public Result queryAddress(String token) {
        int userId = jwtHelper.getUserId(token).intValue();
        LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Address::getUserId, userId);
        List<Address> addresses = addressMapper.selectList(queryWrapper);
        if (!addresses.isEmpty()) {
            return Result.ok(addresses);
        }
        return Result.error("暂无地址信息！");
    }

    /**
     * 根据id查询单个地址信息
     *
     * @param addressId
     * @param
     * @return
     */
    @Override
    public Result queryOneAddress(Integer addressId) {
        LambdaQueryWrapper<Address> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Address::getAddressId, addressId);
        Address address = addressMapper.selectOne(lambdaQueryWrapper);
        if (address != null) {
            return Result.ok(address);
        }
        return Result.error(null);
    }
}




